package com.xiao.rabbitmq.rabbit;

import com.xiao.rabbitmq.utils.JsonTool;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 消息队列服务接口实现
 */
@Service("messageQueueService")
public class MessageQueueServiceImpl implements IMessageQueueService, RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void send(String queueName, String msg) {

        rabbitTemplate.setReturnCallback(this);

        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                System.out.println("HelloSender消息发送失败" + cause + correlationData.toString());
            } else {
                System.out.println("HelloSender 消息发送成功 ");
            }
        });
        rabbitTemplate.convertAndSend(MQConstant.DEFAULT_EXCHANGE, queueName, msg);
    }

    @Override
    public void send(String queueName, String msg, long times) {

        DLXMessage dlxMessage = new DLXMessage(queueName, msg, times);

        MessagePostProcessor processor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration(times + "");
                return message;
            }
        };

        dlxMessage.setExchange(MQConstant.DEFAULT_EXCHANGE);


        rabbitTemplate.convertAndSend(MQConstant.DEFAULT_EXCHANGE,
                MQConstant.DEFAULT_DEAD_LETTER_QUEUE_NAME,
                JsonTool.getJsonStr(dlxMessage), processor);
    }


    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
        System.out.println("sender return success" + message.toString() + "===" + i + "===" + s1 + "===" + s2);
    }
}